/*
 * @Author: leemr lscmr@qq.com
 * @Date: 2023-12-19 09:06:56
 * @LastEditors: leemr lscmr@qq.com
 * @LastEditTime: 2023-12-19 09:11:53
 * @FilePath: \futures-bill\src\utils\request.ts
 * @Description:
 *
 */
import axios from 'axios'
import qs from 'qs'
import { closeToast, showLoadingToast } from 'vant'
import to from 'await-to-js'
import jsonp from 'jsonp'
import { connectUrl, getSecret } from './util'

const instance = axios.create({
  // baseURL:  process.env.GATSBY_API_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  },
  validateStatus() {
    // 使用async-await，处理reject情况较为繁琐，所以全部返回resolve，在业务代码中处理异常
    return true
  },
  transformResponse: [
    (data) => {
      if (typeof data === 'string' && data.startsWith('{'))
        data = JSON.parse(data)

      return data
    },
  ],
})

const BrowserId = useLog()
const Token = useLogin()
const uniqueId = getSecret()

/* post接口方法 */
export async function post(
  url: string,
  params?: Record<string, unknown>,
): Promise<any> {
  if (params?.showLoading) {
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
    })
  }

  if (params?.showLoading)
    delete params.showLoading
  const id = await BrowserId
  const token = await Token
  return to(new Promise((resolve, reject) => {
    instance
      .post(url, qs.stringify({ ...params, BrowserId: id, token, uniqueId, _time: new Date().getTime() }))
      .then(({ data }) => {
        resolve(data)
        closeToast()
      })
      .catch((err) => {
        reject(err)
        closeToast()
      })
  }))
}

/* get接口方法 */
export async function get(
  url: string,
  params?: Record<string, unknown>,
): Promise<any> {
  return to(new Promise((resolve, reject) => {
    instance
      .get(url, params)
      .then((res) => {
        let result = res.data
        result = result.slice(1)
        result = result.replace(')', '')
        result = JSON.parse(result)
        resolve(result)
        closeToast()
      })
      .catch((err) => {
        reject(err)
        closeToast()
      })
  }))
}

/* post接口方法 */
export async function logPost(
  url: string,
  params?: Record<string, unknown>,
): Promise<any> {
  return to(new Promise((resolve, reject) => {
    instance
      .post(url, qs.stringify(params))
      .then((res) => {
        resolve(res.data)
        closeToast()
      })
      .catch((err) => {
        reject(err)
        closeToast()
      })
  }))
}

/**
 * 导出jsonp请求方法
 * @url 请求地址
 * @params post请求参数
 */

export function jsonpHttp(
  url: string,
  data?: any,
  options?: any,
): Promise<any> {
  url += (!url.includes('?') ? '?' : '&') + connectUrl(data)
  return new Promise((resolve, reject) => {
    jsonp(url, options, (err, data) => {
      if (!err)
        resolve(data)
      else
        reject(err)
    })
  })
}
